<?php
namespace app\manager\controller;

use app\common\lib\AdminController;
use app\manager\model\ManagerModel;
use app\manager\model\ManagerRoleModel;
use app\manager\model\PermissionFileCache;
use think\Controller;
use think\Request;

class ManagerRoleController extends AdminController
{
    /**
     * 角色分配
     *
     * @return mixed|\think\response\Json
     * @throws \think\Exception
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function index()
    {
        $data = $_REQUEST;
        if (!isset($data['manager_id'])) {
            return json(['code' => 0, 'msg' => 'param or manager_id no exist']);
        }

        $model = new ManagerRoleModel();
        if (request()->isPost()) {
            if (empty($data['role_list'])) {
                return json(['code' => 0, 'msg' => '角色不能为空']);
            }
            $res = $model->dispatch($data);
            if (!$res) {
                return json(['code' => 0, 'msg' => $model->error_msg?:$model->getError()]);
            }
            // 清空文件权限缓存
            $fileCacheM = new PermissionFileCache();
            $fileCacheM->rmPermission();

            return json(['code' => 1, 'msg' => 'success']);
        }

        $role_list = $model->roleList($data['manager_id']);
        $managerM = new ManagerModel();
        $manager = $managerM->where(['id' => $data['manager_id']])->find();
        $username = $manager->getData('username');
        $this->assign('role_list', $role_list);
        $this->assign('username', $username);
        $this->assign('manager_id', $data['manager_id']);
        return $this->fetch();
    }
}
